<template>
  <div>
    <Dialog
      :title="title"
      :visible="visible"
      :button-text="textBtn"
      :loading="loading"
      class="single-column"
      @confirm="submitForm"
      @close="handleClose"
    >
      <el-form
        ref="triageFormRef"
        :model="triageForm"
        :rules="triageFormRules"
        label-width="100px"
      >
        <el-form-item label="顾客：" prop="customerName">
          <el-autocomplete
            v-model="triageForm.customerName"
            :fetch-suggestions="querySearch"
            placeholder="姓名、手机号、编号"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item label="项目：" prop="projectName">
          <el-select
            v-model="triageForm.projectName"
            value-key="id"
            class="el-select-y"
            @change="handleSelectProject"
          >
            <el-option
              v-for="item in projectNameOptions"
              :key="item.id"
              :label="item.projectName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="咨询师：" prop="counselor">
          <el-select
            v-model="triageForm.counselor"
            value-key="id"
            class="el-select-y"
            @change="handleSelectFaceDoctorName"
          >
            <el-option
              v-for="item in faceDoctorOptions"
              :key="item.id"
              :label="item.usrName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主治医生：" prop="doctor">
          <el-select
            v-model="triageForm.doctor"
            value-key="id"
            class="el-select-y"
            @change="handleSelectFaceDoctorNames"
          >
            <el-option
              v-for="item in faceDoctorOptions1"
              :key="item.id"
              :label="item.usrName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预约：" prop="isAppointment">
          <el-switch
            v-model="isAppointment"
            active-color="#13ce66"
            inactive-color="#eeeeef"
          />
        </el-form-item>
        <el-form-item v-if="isAppointment" label="预约时间：" prop="appointmentTime">
          <el-date-picker
            v-model="triageForm.appointmentTime"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            range-separator="至"
            class="el-date-picker-y"
            :default-time="['07:00:00','23:59:59']"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item v-if="isAppointment" label="预约说明：" prop="appointmentRemark">
          <el-input v-model="triageForm.appointmentRemark" class="textarea-border" type="textarea" resize="none" />
        </el-form-item>
        <!-- <el-form-item label="医生助理：" prop="doctorHelperName">
          <el-select v-model="triageForm.doctorHelperName" value-key="id">
            <el-option
              v-for="item in faceDoctorOptions"
              :key="item.id"
              :label="item.usrName"
              :value="item.usrName"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog/index";
import { lookup } from "@/utils/common.js";
export default {
  components: {
    Dialog,
  },
  props: {
    textBtn: {
      type: String,
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      pickerMinDate: "", // 第一次选中的时间
      pickerOptions: {
        onPick: obj => {
          this.pickerMinDate = new Date(obj.minDate).getTime();
        },
        disabledDate: (time) => {
          if (this.pickerMinDate) {
            const targetDateTime = new Date(this.pickerMinDate);
            const currentDateTime = new Date(time);
            if (currentDateTime.getDate() === targetDateTime.getDate() && currentDateTime.getMonth() === targetDateTime.getMonth()) {
              return false;
            }
            return true;
          } else {
            const times = Date.now() - 24 * 60 * 60 * 1000;
            return time.getTime() < times;
          }
        },
      },
      isAppointment: true,
      triageForm: {},
      selectCustomer: {},
      selectProject: {},
      projectNameOptions: [],
      faceDoctorOptions: [],
      faceDoctorOptions1: [],
      baseUrl: '',
      loading: false,
      title: '治疗登记',
      triageFormRules: {
        customerName: [
          {
            required: true,
            message: "请输入顾客姓名",
            trigger: ["blur", "change"],
          },
        ],
        projectName: [
          { required: true, message: "请选择项目", trigger: "change" },
        ],
        appointmentTime: [
          { required: true, message: "请选择预约时间", trigger: "change" },
        ],
      },
      // pickerOptions: {
      //   disabledDate(time) {
      //     const times = Date.now() - 24 * 60 * 60 * 1000;
      //     return time.getTime() < times;
      //   },
      // },
    };
  },
  methods: {
    // // 开始时间 控制结束时间
    // changeEnd() {
    //   this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, {
    //     disabledDate: (time) => {
    //       return time.getTime() > Date.now() && time.getTime() < Date.now() + 1;
    //     },
    //   });
    // },
    addTriage(val, row) {
      this.faceDoctorOptions = lookup('咨询师');
      this.faceDoctorOptions1 = lookup('主治医生');
      this.loading = false;
      if (val === 'add') {
        this.title = "增加治疗登记";
        this.baseUrl = 'department/diagnose/curetask/addTreatList';
        if (row) {
          this.triageForm = JSON.parse(JSON.stringify(row));
          this.selectCustomer.customerId = this.triageForm.customerId;
          this.getProjectName();
        }
      } else if (val === 'eadit') {
        this.title = "修改治疗登记";
        this.baseUrl = 'department/diagnose/curetask/eaditTreatList';
        this.triageForm = JSON.parse(JSON.stringify(row));
        this.triageForm.appointmentTime = [this.triageForm.appointmentBeginTime, this.triageForm.appointmentEndTime];
        this.triageForm.isAppointment === '是' ? this.isAppointment = true : this.isAppointment = false;
        this.selectCustomer.customerId = this.triageForm.customerId;
        this.getProjectName();
      } else
      if (row) {
        this.triageForm = {
          customerName: row.customerName,
          projectName: row.projectName,
          intentCaseId: row.projectId,
          intentCaseNo: row.productNo,
          intentCaseType: row.productAttributes,
          orderListId: row.id,
          counselor: row.receiverName,
        };
        Object.assign(this.triageForm, row);
      }
      this.loadAll();
      this.getFaceDoctorData();
    },
    toSendBtnTriage(row) {
      this.loadAll();
      this.getFaceDoctorData();
      this.triageForm = row;
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        if (restaurant.value) {
          return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
          );
        } else {
          return null;
        }
      };
    },
    handleSelect(item) {
      this.selectCustomer = {
        customerId: item.id,
        customerName: item.name,
        sex: item.sex,
        customerCode: item.code,
        customerPhone: item.phone,
      };
      Object.assign(this.triageForm, this.selectCustomer);
      // this.projectNameOptions = [];
      if (item.id) {
        this.getProjectName();
      }
    },
    handleSelectProject(item) {
      // this.triageForm.projectName = item.usrName;
      this.triageForm.projectId = item.projectId;
      this.selectProject = {
        intentCaseId: item.projectId,
        projectName: item.projectName,
        intentCaseNo: item.productNo,
        productAttributes: item.productAttributes,
        orderListId: item.id,
      };
      Object.assign(this.triageForm, this.selectProject);
    },
    handleSelectFaceDoctorName(item) {
      this.triageForm.counselor = item.usrName;
      this.triageForm.counselorId = item.id;
    },
    handleSelectFaceDoctorNames(item) {
      this.triageForm.doctor = item.usrName;
      this.triageForm.doctorId = item.id;
    },
    async loadAll() {
      const res = await this.$api["reception/subscribe/findall"]();
      if (res.code === 200) {
        res.data.map((item) => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
    },
    // 顾客已购项目
    async getProjectName() {
      const res = await this.$api[
        "reception/subscribe/customerIdAllByOrderList"
      ]({ customerId: this.selectCustomer.customerId });
      if (res.code === 200) {
        this.projectNameOptions = res.data;
      }
    },
    async getFaceDoctorData() {
      // const faceDoctorData = await this.$api["reception/triage/AllByJobName"]({
      //   hospitalJobName: "主治医生",
      // });
      // if (faceDoctorData.code === 200) {
      //   this.faceDoctorOptions = faceDoctorData.data;
      // }
    },
    submitForm() {
      this.$refs.triageFormRef.validate(async(valid) => {
        if (valid) {
          this.triageForm.deptName = this.$store.getters.currentUserInfo.deptUsrList[0].deptName;
          this.triageForm.deptId = this.$store.getters.currentUserInfo.deptUsrList[0].deptId;
          this.triageForm.treatType = "治疗/复查";
          this.isAppointment ? this.triageForm.isAppointment = '是' : this.triageForm.isAppointment = '否';
          if (this.isAppointment) {
            this.triageForm.appointmentBeginTime = new Date(this.triageForm.appointmentTime[0]).valueOf();
            this.triageForm.appointmentEndTime = new Date(this.triageForm.appointmentTime[1]).valueOf();
          }
          this.triageForm.appointmentTime = '';
          this.loading = true;
          if (this.title === '增加治疗登记') {
            this.$api[this.baseUrl](this.triageForm).then((res) => {
              if (res.code !== 200) return this.$massage.info('增加治疗登记失败');
              this.loading = false;
              this.$massage.success('增加治疗登记成功');
            });
          } else if (this.title === '修改治疗登记') {
            this.$api[this.baseUrl](this.triageForm).then((res) => {
              if (res.code !== 200) return this.$massage.info('修改治疗登记失败');
              this.loading = false;
              // this.$massage.success('修改治疗登记成功');
            });
          } else if (this.title === "添加分诊" || this.title === "添加任务") {
            this.baseUrl = 'reception/triage/createTriage';
            const res = await this.$api[this.baseUrl]({
              ...this.triageForm,
            });
            if (res.code !== 200) return this.$message.error("新增分诊失败！");
            this.loading = false;
            this.$message.success("新增分诊成功！");
          } else {
            this.baseUrl = 'reception/triage/updataTriage';
            const res = await this.$api[this.baseUrl]({
              ...this.triageForm,
            });
            if (res.code !== 200) return this.$message.error("修改分诊失败！");
            this.loading = false;
            this.$message.success("修改分诊成功！");
          }
          this.$emit("update:visible", false);
          this.$emit('success');
          this.$refs.triageFormRef.resetFields();
        }
      });
    },
    // 关闭
    handleClose() {
      this.$emit("update:visible", false);
      this.triageForm = {};
      this.$nextTick(() => {
        this.$refs["triageFormRef"].clearValidate();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-autocomplete {
  width: 100%;
}
/deep/.el-textarea__inner{
  height: 66px;
  border: 1px solid #797979;
}
/deep/.el-textarea__inner{
  border: 1px solid #D3DFF7
}
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
</style>
